// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.parsers;

import java.io.File;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import net.web2me.api.AbstractBaseParser;
import net.web2me.api.ParserException;
import net.web2me.api.ProcessFinishedException;
import net.web2me.api.util.DocumentGenerator;
import net.web2me.api.util.Downloader;
import net.web2me.api.util.SiteStreamGenerator;
import net.web2me.api.util.UtilityException;

public class UbbiFotologParser extends AbstractBaseParser {
	
	private Logger logger = Logger.getLogger(UbbiFotologParser.class);
	private boolean firstTime = true;
	private String firstPicLink = null;
	private String nextImageLink = "";
	private Downloader downloader = new Downloader();

	@Override
	public void process(String stream) throws ParserException {
		
		if(isFirstTime()){
			setFirstTime(false);
			
			String user = getUserName();
			String dir = getDir() + "/" + user;
			
			File downDir = new File(dir);
			
			if( downDir.exists() && downDir.isDirectory() ){
				setDir( downDir.toString() );
			}else{
				if(!downDir.mkdirs()){
					throw new ParserException("Can't create the directory \"" + dir + "\"");
				}else{
					setDir(getDir() + "/" + user);
				}
			}
			
			if(isFirstPicture()){
				nextImageLink = "previous";
			}else{
				nextImageLink = "next";
			}
		}
		
		//Download the image from the current page
		try {
			saveCurrentImage(stream);
		} catch (Exception e) {
			logger.error("Exception caught", e);
			throw new ParserException(e);
		}
		
		try {
			String site;
			String nextLink = getNextPictureLink(stream);
			
			if(nextLink != null){
				site = SiteStreamGenerator.getStream(nextLink);
				process(site);
			}
		} catch (UtilityException e) {
			logger.error("UtilityException caught", e);
			throw new ParserException(e);
		} catch (Exception e){
			logger.error("Exception caught", e);
			throw new ParserException(e);
		}
	}
	
	private String getNextPictureLink(String stream) throws Exception {
		Document doc = null;
		doc = DocumentGenerator.generate(stream);
		
		NodeList uls = doc.getElementsByTagName("ul");
		
		for(int i = 0; i < uls.getLength(); i++){
			Element ul = (Element) uls.item(i);
			
			if(ul.getAttribute("class").equals("mainphotonav")){
				
				NodeList lis = ul.getElementsByTagName("li");
				
				for(int j = 0; j < lis.getLength(); j++){
					Element li = (Element) lis.item(j);
					
					if(li.getAttribute("class").equals(nextImageLink)){
						Element link = (Element) li.getElementsByTagName("a").item(0);
						if(link != null){
							return link.getAttribute("href");
						}else{
							logger.debug("No link found, end reached.");
							//return getNextPictureLink(stream);
						}
					}
				}
				
			}
		}
		
		return null;
	}

	private boolean isFirstPicture() {
		// Check if the URL is not the first pic.
		// If isn't, load the first page and save the firstPicIdentifier
		String tmpUser = getUrl().replace("http://www.fotolog.com/", "");
		tmpUser = tmpUser.replace("http://www1.fotolog.com/", "");
		tmpUser = tmpUser.replace("http://ubbiar.fotolog.com/", "");
		
		return !(tmpUser.indexOf("/") > -1);
	}
	
	/**
	 * Saves the image located in the current page
	 * @param pageStream
	 * @throws Exception
	 */
	private void saveCurrentImage(String pageStream) throws ParserException, Exception{
		Document doc = null;
		doc = DocumentGenerator.generate(pageStream);
		
		NodeList divs = doc.getElementsByTagName("div");
		
		for(int i = 0; i < divs.getLength(); i++){
			Element div = (Element)divs.item(i);
			
			if( div.getAttribute("id").equals("mainphoto") ){
				NodeList imgs = div.getElementsByTagName("img");
				Element img = (Element) imgs.item(0);
				
				try {
					String url = img.getAttribute("src");
					
					if(firstPicLink == null){
						firstPicLink = url;
					}else{
						if(firstPicLink.equals(url)){
							throw new ProcessFinishedException();
						}
					}
					
					downloader.setUrl(url);
					downloader.setDestinyDirectory(getDir());
					downloader.download();
					break;
				} catch (UtilityException e) {
					logger.error("UtilityException caught", e);
					throw new ParserException(e);
				}
			}
		}
		
	}

	/**
	 * Gets the user name from the URL
	 * @return the user name
	 */
	private String getUserName(){
		
		/****
			Actually, the Ubbi Fotolog URL can be formed in three ways:
			1) http://www.fotolog.com/user
			2) http://www.fotolog.com/user/12345 (The number is the picture indentifier)
			3) http://ubbiar.fotolog.com/user/12345 (The number is the picture indentifier)
		*****/
		
		String user = getUrl().replace("http://www.fotolog.com/", "");
		user = user.replace("http://ubbiar.fotolog.com/", "");
		
		if( user.indexOf("/") > -1){
			//This case is: user/12345
			//We have to remove the user identifier
			user = user.replaceAll("\\d", "");
		}
		
		user = user.replace("/", "");
		
		logger.debug("Returning user name \"" + user + "\"");
		return user;
	}
	
	private boolean isFirstTime(){
		return firstTime;
	}
	
	private void setFirstTime(boolean firstTime){
		this.firstTime = firstTime;
	}
}
